package cn.com.longfuinfo.wx.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

import org.apache.log4j.Logger;

import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.upload.UploadFile;
import com.jfinal.weixin.sdk.api.JsTicket;
import com.jfinal.weixin.sdk.api.JsTicketApi;
import com.jfinal.weixin.sdk.api.JsTicketApi.JsApiType;

import cn.com.longfuinfo.wx.common.CacheHolder;
import cn.com.longfuinfo.wx.common.Constants;
import cn.com.longfuinfo.wx.dao.User;
import cn.com.longfuinfo.wx.dao.WxUser;
import cn.com.longfuinfo.wx.domain.AjaxResult;
import cn.com.longfuinfo.wx.kit.CommonKit;
import cn.com.longfuinfo.wx.kit.FTPClientKit;

public class BaseController extends Controller{
	protected Logger logger = Logger.getLogger(getClass());
	
	/**
	 * 获取当前定位或选择的城市
	 */
	public String getCurrentCity(){
		if(StrKit.isBlank(getSessionAttr(Constants.cityId))){
			return "187";
		}else{
			return getSessionAttr(Constants.cityId);
		}
	}
	public int getCurrentCityid(){
		return 187;
	}
	
	/**
	 * 获取当前登录用户
	 */
	public User getCurrentUser(){
		return getSessionAttr(Constants.USER);
	}
	public int getCurrentUserid(){
		return ((User)getSessionAttr(Constants.USER)).getInt("id");
	}
	
	/**
	 * 获取当前进入的微信用户
	 */
	public WxUser getCurrentWxUser(){
		return getSessionAttr(Constants.WX_USER);
	}
	public int getCurrentWxUserid(){
		return ((WxUser)getSessionAttr(Constants.WX_USER)).getInt("id");
	}
	
	/**
	 * 获取JSAPI所需的参数
	 * @param url 要跳转的页面地址
	 */
	public void getJSApiParams(String url){
		StringBuffer params = new StringBuffer();
		//参数1：jsapi_ticket
		//注：因为jsapi_ticket失效期为7200秒，如果频繁获取，会影响接口调用，所以将此参数放入缓存中，每次使用都先从缓存中取，如果失效，则再重新获取
		String jsapi_ticket;
		if(CacheHolder.has("JSAPI_TICKET")){
			//从缓存中取
			jsapi_ticket = CacheHolder.getStr("JSAPI_TICKET");
			logger.error("从缓存中取出JSAPI_TICKET："+jsapi_ticket);
		}else{
			//重新获取
			JsTicket jsTicket = JsTicketApi.getTicket(JsApiType.jsapi);
			if(jsTicket.isAvailable()){
				jsapi_ticket = jsTicket.getTicket();
				CacheHolder.cache("JSAPI_TICKET", jsapi_ticket, 7200*1000);
			}else{
				//获取jsapi_ticket失败，请作相应处理
				jsapi_ticket = "";
			}
			logger.error("接口响应JSAPI_TICKET："+jsapi_ticket);
		}
		params.append("jsapi_ticket=").append(jsapi_ticket);
		//参数2：随机字符串
		String noncestr = CommonKit.getUUID();
		params.append("&noncestr=").append(noncestr);
		//参数3：时间戳
		String timestamp = Long.toString(System.currentTimeMillis() / 1000);
		params.append("&timestamp=").append(timestamp);
		//参数4：网页地址
		params.append("&url=").append(url);
		//签名
		String signature = null;
		try{
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(params.toString().getBytes("UTF-8"));
            byte[] hash = crypt.digest();
            Formatter formatter = new Formatter();
            for (byte b : hash){
                formatter.format("%02x", b);
            }
            signature = formatter.toString();
            formatter.close();
        }catch (NoSuchAlgorithmException e){
            e.printStackTrace();
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
		
		logger.error("jssdk所需要的参数："+params);
		logger.error("signature："+signature);
		logger.error("appId："+PropKit.get("wx.appId"));
		//将js初始化时所需要的参数返回给页面
		setAttr("appId", PropKit.get("wx.appId"));
		setAttr("timestamp", timestamp);
		setAttr("nonceStr", noncestr);
		setAttr("signature", signature);
	}
	
	/**
	 * 上传图片至指定FTP目录，并返回重新生成的UUID文件名（含扩展名部分，可直接保存数据库）
	 */
	protected String uploadToFtp(String ftpPath,UploadFile file) throws IOException{
		//获取文件，并上传至FTP根目录下，用UUID重命名
		String fileName = file.getFileName();
		String extension = fileName.substring(fileName.lastIndexOf("."));
		String newFileName = CommonKit.getUUID();
		FTPClientKit.upload(ftpPath, newFileName + extension, file.getFile());
		return newFileName + extension;
	}
	
	/**
	 * 返回json格式内容
	 */
	public void renderResult(int flag){
		logger.error(JsonKit.toJson(new AjaxResult(flag)));
		this.renderText(JsonKit.toJson(new AjaxResult(flag)));
	}
	
	public void renderResult(int flag,String message){
		logger.error(JsonKit.toJson(new AjaxResult(flag,message)));
		this.renderText(JsonKit.toJson(new AjaxResult(flag,message)));
	}
	
	public void renderResult(int flag,String message,Object object){
		logger.error(JsonKit.toJson(new AjaxResult(flag,message,object)));
		this.renderText(JsonKit.toJson(new AjaxResult(flag,message,object)));
	}
	
	public void renderResult(int flag,Object object){
		logger.error(JsonKit.toJson(new AjaxResult(flag,object)));
		this.renderText(JsonKit.toJson(new AjaxResult(flag,object)));
	}
	
	public void renderSuccess(){
		renderResult(AjaxResult.FLAG_SUCCESS);
	}
	
	public void renderSuccess(String message){
		renderResult(AjaxResult.FLAG_SUCCESS,message);
	}
	
	public void renderSuccess(Object object){
		renderResult(AjaxResult.FLAG_SUCCESS,object);
	}
	
	public void renderSuccess(String message,Object object){
		renderResult(AjaxResult.FLAG_SUCCESS,message,object);
	}
	
	public void renderFailed(){
		renderResult(AjaxResult.FLAG_FAILED);
	}
	
	public void renderFailed(String message){
		renderResult(AjaxResult.FLAG_FAILED,message);
	}
}
